//
//  Tool.m
//  就到
//
//  Created by MT on 2017/11/13.
//  Copyright © 2017年 MT. All rights reserved.
//

#import "Tool.h"

@implementation Tool

+ (BOOL)isLogined
{
    return (! [Tool isBlankString:[Tool getLocalDataValue:kAccessTokenKey]]);
}

/*
 设置本地数据库key对应的数据
 */
+ (void)setLocalDataValue: (NSString *)aValue key:(NSString *)aKey
{
    if (nil == USER_DEFAULT || nil == aKey) {
        return ;
    }
    [USER_DEFAULT setObject:aValue forKey:aKey];
    [USER_DEFAULT synchronize];
}
/*
 读取本地数据库的Value
 */
+ (id)getLocalDataValue:(NSString *)aKey
{
    if (nil == aKey) {
        return nil;
    }
    return [USER_DEFAULT objectForKey:aKey];
}
/*
 设置本地数据库key对应的bool数据
 */
+ (void)setLocalDataBoolen: (BOOL)aValue key:(NSString *)aKey
{
    if (nil == USER_DEFAULT || nil == aKey) {
        return;
    }
    [USER_DEFAULT setBool:aValue forKey:aKey];
    [USER_DEFAULT synchronize];
}
/*
 获取本地数据库对应的bool数据
 */
+ (BOOL)getLocalDataBoolen: (NSString *)aKey
{
    BOOL bRet = false;
    if (nil == USER_DEFAULT || nil == aKey) {
        bRet = false;
    }else{
        bRet = [USER_DEFAULT boolForKey:aKey];
    }
    
    return bRet;
}
/*
 设置本地数据库key对应的array数据
 */
+ (void)setLocalDataArray: (NSMutableArray *)array key:(NSString *)aKey
{
    if (nil == USER_DEFAULT || nil == aKey) {
        return;
    }
    [USER_DEFAULT setObject:array forKey:aKey];
    [USER_DEFAULT synchronize];
}
/*
 获取本地数据库对应的array数据
 */
+ (id)getLocalDataArray: (NSString *)aKey
{
    if (nil == aKey) {
        return nil;
    }
    return [USER_DEFAULT objectForKey:aKey];
}
/*
 设置本地数据库key对应的dictionary数据
 */
+ (void)setLocalDataDictionary: (NSDictionary *)dictionary key:(NSString *)aKey
{
    if (nil == USER_DEFAULT || nil == aKey) {
        return;
    }
    [USER_DEFAULT setObject:dictionary forKey:aKey];
    [USER_DEFAULT synchronize];
}
/*
 获取本地数据库对应的dic数据
 */
+ (id)getLocalDataDictionary: (NSString *)aKey
{
    if (nil == aKey) {
        return nil;
    }
    return [USER_DEFAULT objectForKey:aKey];
}
/*
 设置本地数据库key对应的对象数据
 */
+ (void)setLocalDataObject: (NSObject *)Object key:(NSString *)aKey
{
    if (nil == USER_DEFAULT || nil == aKey) {
        return;
    }
    [USER_DEFAULT setObject:Object forKey:aKey];
    [USER_DEFAULT synchronize];
}
/*
 获取本地数据库对应的对象数据
 */
+ (id)getLocalDataObject: (NSString *)aKey
{
    if (nil == aKey) {
        return nil;
    }
    return [USER_DEFAULT objectForKey:aKey];
}

//对象转json字符串
+ (NSString*)DataTOjsonString:(id)object
{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    NSString *strUrl = [jsonString stringByReplacingOccurrencesOfString:@" " withString:@""];  //去掉空格
    
    NSString *str = [strUrl stringByReplacingOccurrencesOfString:@"\n" withString:@""];//替换字符

    return str;
}

//判断字符串是否为空
+ (BOOL) isBlankString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
 }

+ (NSMutableDictionary *)returnSafeDictionary:(NSDictionary *)dic{
    NSMutableDictionary *mutabledic = [[NSMutableDictionary alloc] initWithDictionary:dic];
    NSArray *valueArray= [dic allKeys];
    for (NSString *key in valueArray) {
        if ([[mutabledic objectForKey:key]isEqual:[NSNull null]]) {
            [mutabledic setObject:@"" forKey:key];
        }
    }
    return mutabledic;
}

//验证手机号的正则
+ (BOOL) IsPhoneNumber:(NSString *)number
{
    NSString *phoneRegex1=@"1[34578]([0-9]){9}";
    NSPredicate *phoneTest1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex1];
    return  [phoneTest1 evaluateWithObject:number];
}

// 设置密码的位数
+ (BOOL) IsCorrectPassword:(NSString *)phoneStr{
    NSString * regex = @"^[A-Za-z0-9]{6,16}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:phoneStr];
}

// 正则匹配用户密码6-16位数字和字母组合
+ (BOOL)checkPassword:(NSString *) password
{
    NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,16}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:password];
    return isMatch;
    
}

//获取电话当前网络类型
+ (PhoneNetType)getCurrentPhoneNetType
{
    PhoneNetType phoneNetPype = PNT_UNKOWN;
    if ([[self getNetWorkStates]isEqualToString:@"2G"]
        || [[self getNetWorkStates]isEqualToString:@"3G"]
        || [[self getNetWorkStates]isEqualToString:@"4G"]) {
        
        phoneNetPype = PNT_2G3G;
    }
    else if([[self getNetWorkStates]isEqualToString:@"WIFI"]){
        
        phoneNetPype = PNT_WIFI;
    }
    return phoneNetPype;
}
//取网络类型
+ (NSString *)getNetWorkStates
{
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews];
    NSString *state = [[NSString alloc]init];
    int netType = 0;
    for (id child in children) {
        if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
            //获取到状态栏
            netType = [[child valueForKeyPath:@"dataNetworkType"]intValue];
            NSLog(@"netType:::::%d",netType);
            switch (netType) {
                case 0:
                    state = @"无网络";
                    break;
                case 1:
                    state = @"2G";
                    break;
                case 2:
                    state = @"3G";
                    break;
                case 3:
                    state = @"4G";
                    break;
                case 5:
                    state = @"WIFI";
                    break;
                    
                default:
                    break;
            }
            
        }
    }
    return state;
}

//判断字符串是否包含汉字
+ (BOOL)isContainChinese:(NSString *)string
{
    for (int i = 0; i < [string length]; i++) {
        unichar a = [string characterAtIndex:i];
        if (a >= 0x4e00 && a <= 0x9fff) {
            return YES;
        }
    }
    return NO;
}

//判断是否是纯数字
+ (BOOL)isStringPureInt:(NSString *)string
{
    NSScanner *scanner = [NSScanner scannerWithString:string];
    int val;
    return [scanner scanInt:&val] && [scanner isAtEnd];
}

//计算textvie动态高度
+ (float) heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width{    UITextView *detailTextView = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, width, 0)];    detailTextView.font = [UIFont systemFontOfSize:fontSize];
    detailTextView.text = value;
    CGSize deSize = [detailTextView sizeThatFits:CGSizeMake(width,CGFLOAT_MAX)];
    return deSize.height;
}

//计算文字长度
+ (CGFloat )widthForLabel:(NSString *)text fontSize:(CGFloat)font
{
    CGSize size = [text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:font], NSFontAttributeName, nil]];
    return size.width;
}
//获取磁盘缓存文件大小
+ (float)readCacheSize
{
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES) firstObject];
    NSFileManager * manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath :cachePath]) return 0 ;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:cachePath] objectEnumerator];
    NSString * fileName;
    long long folderSize = 0 ;
    while ((fileName = [childFilesEnumerator nextObject]) != nil ){
        //获取文件全路径
        NSString * fileAbsolutePath = [cachePath stringByAppendingPathComponent:fileName];
        NSFileManager * manager = [NSFileManager defaultManager];
        if ([manager fileExistsAtPath :fileAbsolutePath]){
            folderSize += [[manager attributesOfItemAtPath :fileAbsolutePath error : nil] fileSize];
        }
    }
    return folderSize/( 1024.0 * 1024.0);
}

//清除缓存
+ (void)clearFile
{
    NSString * cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject];
    NSArray * files = [[NSFileManager defaultManager ] subpathsAtPath :cachePath];
    //NSLog ( @"cachpath = %@" , cachePath);
    for ( NSString * p in files) {
        
        NSError * error = nil ;
        //获取文件全路径
        NSString * fileAbsolutePath = [cachePath stringByAppendingPathComponent :p];
        
        if ([[NSFileManager defaultManager ] fileExistsAtPath :fileAbsolutePath]) {
            [[NSFileManager defaultManager ] removeItemAtPath :fileAbsolutePath error :&error];
        }
    }
}


//获取当前viewcontroller
+ (UIViewController *)getCurrentVC{
    
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    //app默认windowLevel是UIWindowLevelNormal，如果不是，找到UIWindowLevelNormal的
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    id  nextResponder = nil;
    UIViewController *appRootVC=window.rootViewController;
    //    如果是present上来的appRootVC.presentedViewController 不为nil
    if (appRootVC.presentedViewController) {
        nextResponder = appRootVC.presentedViewController;
    }else{
        UIView *frontView = [[window subviews] objectAtIndex:0];
        nextResponder = [frontView nextResponder];
    }
    
    if ([nextResponder isKindOfClass:[UITabBarController class]]){
        UITabBarController * tabbar = (UITabBarController *)nextResponder;
        UINavigationController * nav = (UINavigationController *)tabbar.viewControllers[tabbar.selectedIndex];
        //        UINavigationController * nav = tabbar.selectedViewController ; 上下两种写法都行
        result=nav.childViewControllers.lastObject;
        
    }else if ([nextResponder isKindOfClass:[UINavigationController class]]){
        UIViewController * nav = (UIViewController *)nextResponder;
        result = nav.childViewControllers.lastObject;
    }else{
        result = nextResponder;
    }
    
    return result;
}

//正则匹配用户身份证号15或18位
+ (BOOL)checkUserIdCard:(NSString *)idCard
{
    if (idCard.length <= 0) {
        return NO;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:idCard];
}


//字典转json
+ (NSString *)convertToJsonData:(NSDictionary *)dict

{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}

//字典转字符串
+ (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] stringByReplacingOccurrencesOfString:@" " withString:@""];
    
}

//验证银行卡号
+ (BOOL) checkCardNo:(NSString*) cardNo{
    int oddsum = 0;     //奇数求和
    int evensum = 0;    //偶数求和
    int allsum = 0;
    int cardNoLength = (int)[cardNo length];
    int lastNum = [[cardNo substringFromIndex:cardNoLength-1] intValue];
    
    cardNo = [cardNo substringToIndex:cardNoLength - 1];
    for (int i = cardNoLength -1 ; i>=1;i--) {
        NSString *tmpString = [cardNo substringWithRange:NSMakeRange(i-1, 1)];
        int tmpVal = [tmpString intValue];
        if (cardNoLength % 2 ==1 ) {
            if((i % 2) == 0){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }else{
            if((i % 2) == 1){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }
    }
    
    allsum = oddsum + evensum;
    allsum += lastNum;
    if((allsum % 10) == 0)
        return YES;
    else
        return NO;
}

//判断银行图标
+ (NSString *) judgeCardImage:(NSString*) cardNo{
    if([cardNo rangeOfString:@"招商银行"].location !=NSNotFound){
        return @"zhaoshang";
    }else if([cardNo rangeOfString:@"中国银行"].location !=NSNotFound){
        return @"zhongguoyinhang";
    }else if([cardNo rangeOfString:@"北京银行"].location !=NSNotFound){
        return @"beijing";
    }else if([cardNo rangeOfString:@"工商银行"].location !=NSNotFound){
        return @"gongshangyinhang";
    }else if([cardNo rangeOfString:@"广发银行"].location !=NSNotFound){
        
        return @"guangfa";
    }else if([cardNo rangeOfString:@"华夏银行"].location !=NSNotFound){
        return @"huaxia";
    }else if([cardNo rangeOfString:@"中信"].location !=NSNotFound){
        return @"zhongxin";
    }else if([cardNo rangeOfString:@"平安"].location !=NSNotFound){
        return @"pingan";
    }
    
    
    else if([cardNo rangeOfString:@"光大"].location !=NSNotFound){
        return @"guangda";
    }
    
    else if([cardNo rangeOfString:@"农业银行"].location !=NSNotFound){
        return @"nongye";
    }else if([cardNo rangeOfString:@"邮政"].location !=NSNotFound){
        return @"youzheng";
    }
    
    
    else if([cardNo rangeOfString:@"建设银行"].location !=NSNotFound){
        return @"jianshe";
    }else if([cardNo rangeOfString:@"交通银行"].location !=NSNotFound){
        return @"jiaotong";
    }else if([cardNo rangeOfString:@"民生银行"].location !=NSNotFound){
        return @"minsheng";
    }else if([cardNo rangeOfString:@"浦发银行"].location !=NSNotFound){
        return @"pufa";
    }else if([cardNo rangeOfString:@"上海银行"].location !=NSNotFound){
        return @"shanghai";
    }else if([cardNo rangeOfString:@"兴业银行"].location !=NSNotFound){
        return @"xingye";
    }else{
        return @"yinhangkayuan";
    }
}

//获取当前时间
+ (NSString *)getCurrentTimeWithFormat:(NSString *)format{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat: format];
    NSString *DateTime = [formatter stringFromDate:date];
    return DateTime;
}

//获取当前时间戳
+ (NSString *)currentTimeStr{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}

//时间戳转时间
+ (NSString *)timestampSwitchTime:(NSInteger)timestamp andFormatter:(NSString *)format{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format]; // （@"YYYY-MM-dd hh:mm:ss"）----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timestamp];
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    return confromTimespStr;
}


+ (CGSize)getImageSizeWithURL:(id)URL{
    NSURL * url = nil;
    if ([URL isKindOfClass:[NSURL class]]) {
        url = URL;
    }
    if ([URL isKindOfClass:[NSString class]]) {
        url = [NSURL URLWithString:URL];
    }
    if (!URL) {
        return CGSizeZero;
    }
    CGImageSourceRef imageSourceRef =     CGImageSourceCreateWithURL((CFURLRef)url, NULL);
    CGFloat width = 0, height = 0;
    if (imageSourceRef) {
        CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSourceRef, 0, NULL);
        if (imageProperties != NULL) {
            CFNumberRef widthNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelWidth);
            if (widthNumberRef != NULL) {
                CFNumberGetValue(widthNumberRef, kCFNumberFloat64Type, &width);
            }
            CFNumberRef heightNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);
            if (heightNumberRef != NULL) {
                CFNumberGetValue(heightNumberRef, kCFNumberFloat64Type, &height);
            }
            CFRelease(imageProperties);
        }
        CFRelease(imageSourceRef);
    }
    return CGSizeMake(width, height);
}


/**
 *  剪切图片为正方形
 *
 *  @param image   原始图片比如size大小为(400x200)pixels
 *  @param newSize 正方形的size比如400pixels
 *
 *  @return 返回正方形图片(400x400)pixels
 */
+ (UIImage *)squareImageFromImage:(UIImage *)image scaledToSize:(CGFloat)newSize {
    CGAffineTransform scaleTransform;
    CGPoint origin;
    
    if (image.size.width > image.size.height) {
        //image原始高度为200，缩放image的高度为400pixels，所以缩放比率为2
        CGFloat scaleRatio = newSize / image.size.height;
        scaleTransform = CGAffineTransformMakeScale(scaleRatio, scaleRatio);
        //设置绘制原始图片的画笔坐标为CGPoint(-100, 0)pixels
        origin = CGPointMake(-(image.size.width - image.size.height) / 2.0f, 0);
    } else {
        CGFloat scaleRatio = newSize / image.size.width;
        scaleTransform = CGAffineTransformMakeScale(scaleRatio, scaleRatio);
        
        origin = CGPointMake(0, -(image.size.height - image.size.width) / 2.0f);
    }
    
    CGSize size = CGSizeMake(newSize, newSize);
    //创建画板为(400x400)pixels
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
        UIGraphicsBeginImageContextWithOptions(size, YES, 0);
    } else {
        UIGraphicsBeginImageContext(size);
    }
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    //将image原始图片(400x200)pixels缩放为(800x400)pixels
    CGContextConcatCTM(context, scaleTransform);
    //origin也会从原始(-100, 0)缩放到(-200, 0)
    [image drawAtPoint:origin];
    
    //获取缩放后剪切的image图片
    image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
}

//获取当前present控制器
+ (UIViewController *)getPresentedViewController
{
    UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *topVC = appRootVC;
    if (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;
    }
    
    return topVC;
}

/** 通过行数, 返回更新时间 */
+ (NSString *)updateTimeForRow:(NSString *)str {
    // 获取当前时时间戳
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
    // 转时间戳
    NSTimeInterval createTime = [str floatValue];
    // 时间差
    NSTimeInterval time = currentTime - createTime;
    
    //秒转分钟
    NSInteger small = time / 60;
    if (small == 0) {
        return [NSString stringWithFormat:@"刚刚"];
    }
    
    
    if (small < 60) {
        return [NSString stringWithFormat:@"%ld分钟前",small];
    }
    
    // 秒转小时
    NSInteger hours = time/3600;
    if (hours<24) {
        return [NSString stringWithFormat:@"%ld小时前",hours];
    }
    //秒转天数
    NSInteger days = time/3600/24;
    if (days < 30) {
        return [NSString stringWithFormat:@"%ld天前",days];
    }
    //秒转月
    NSInteger months = time/3600/24/30;
    if (months < 12) {
        return [NSString stringWithFormat:@"%ld月前",months];
    }
    //秒转年
    NSInteger years = time/3600/24/30/12;
    return [NSString stringWithFormat:@"%ld年前",years];
}

#pragma mark -- image转化成Base64位
+ (NSString *)imageChangeBase64: (UIImage *)image{
    
    NSData   *imageData = nil;
    //NSString *mimeType  = nil;
//    if ([self imageHasAlpha:image]) {
//
//        imageData = UIImagePNGRepresentation(image);
//        //mimeType = @"image/png";
//    }else{
    
        imageData = UIImageJPEGRepresentation(image, 0.3f);
        //mimeType = @"image/jpeg";
//    }
    return [NSString stringWithFormat:@"%@",[imageData base64EncodedStringWithOptions: 0]];
}

+ (BOOL)imageHasAlpha:(UIImage *)image{
    
    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(image.CGImage);
    return (alpha == kCGImageAlphaFirst ||
            alpha == kCGImageAlphaLast ||
            alpha == kCGImageAlphaPremultipliedFirst ||
            alpha == kCGImageAlphaPremultipliedLast);
}

//urlEncode编码
+ (NSString *)urlEncodeStr:(NSString *)input{
    NSString *charactersToEscape = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\| ";
    NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
    NSString *upSign = [input stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
    return upSign;
}

//urlEncode解码
+ (NSString *)decoderUrlEncodeStr: (NSString *) input{
    NSMutableString *outputStr = [NSMutableString stringWithString:input];
    [outputStr replaceOccurrencesOfString:@"+" withString:@"" options:NSLiteralSearch range:NSMakeRange(0,[outputStr length])];
    return [outputStr stringByRemovingPercentEncoding];
}

//签名排序
+ (NSString *)sortSign:(NSDictionary *)dic{
    NSMutableDictionary *mutableDic = [NSMutableDictionary dictionaryWithDictionary:dic];
    mutableDic[@"key"] = @"88ylb@)!*";
    NSArray *keyArray = [mutableDic allKeys];
    NSArray *sortArray = [keyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    NSMutableArray *valueArray = [NSMutableArray array];
    for (NSString *sortString in sortArray) {
        [valueArray addObject:[mutableDic objectForKey:sortString]];
    }
    NSMutableArray *signArray = [NSMutableArray array];
    for (int i = 0; i < sortArray.count; i++) {
        NSString *keyValueStr = [NSString stringWithFormat:@"%@=%@",sortArray[i],valueArray[i]];
        [signArray addObject:keyValueStr];
    }
    NSString *sign = [signArray componentsJoinedByString:@"&"];
    NSString *signMD5 = [self md5:sign];
    
    return signMD5;
}

+ (NSString *) md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    
    NSNumber *num = [NSNumber numberWithUnsignedLong:strlen(cStr)];
    CC_MD5( cStr,[num intValue], result );
    
    return [[NSString stringWithFormat:
             @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];
}


+ (void)showAlert:(NSString *)title
          message:(NSString *)message
             sure:(NSString *)sure
           cancel:(NSString *)cancel
      clickedSure:(void(^)(void))sureBlock
{
    UIAlertController *contoller = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    if (sure.length > 0) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:sure style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            if (sureBlock) { sureBlock(); }
        }];
        [contoller addAction:action];
    }
    if (cancel.length > 0) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:cancel style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }];
        [action setValue:[[UIColor redColor] colorWithAlphaComponent:0.75] forKey:@"titleTextColor"];
        [contoller addAction:action];
    }
    
    [[self getCurrentVC] presentViewController:contoller animated:YES completion:^{ }];
}

@end
